import 'package:flutter/material.dart';

import 'package:focus_detector_v2/focus_detector_v2.dart';
import 'package:visibility_detector/visibility_detector.dart';

mixin PageVisibilityMixin<T extends StatefulWidget> on State<T>
    implements WidgetsBindingObserver {
  bool _isVisible = false;
  bool _isAppInForeground = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  /// 页面可见（例如从别的 tab 回到当前 tab）
  @protected
  void onPageVisible() {}

  /// 页面隐藏（例如切换到别的 tab）
  @protected
  void onPageHidden() {}

  /// App 从后台回到前台
  @protected
  void onAppResumed() {}

  /// App 进入后台
  @protected
  void onAppPaused() {}

  /// 构建页面时使用，自动嵌套监听
  Widget buildPageVisibilityDetector(BuildContext context, Widget child) {
    return VisibilityDetector(
      key: ObjectKey(widget),
      onVisibilityChanged: (info) {
        final visible = info.visibleFraction > 0.01;
        if (visible && !_isVisible) {
          _isVisible = true;
          onPageVisible();
        } else if (!visible && _isVisible) {
          _isVisible = false;
          onPageHidden();
        }
      },
      child: FocusDetector(
        onFocusGained: () {
          if (!_isVisible) {
            _isVisible = true;
            onPageVisible();
          }
        },
        onFocusLost: () {
          if (_isVisible) {
            _isVisible = false;
            onPageHidden();
          }
        },
        child: child,
      ),
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        _isAppInForeground = true;
        onAppResumed();
        break;
      case AppLifecycleState.paused:
        _isAppInForeground = false;
        onAppPaused();
        break;
      default:
        break;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
